import requests
from abc import ABC, abstractmethod

class PaymentResult:
    def __init__(self, success, message):
        self.success = success
        self.message = message

class PaymentError(Exception):
    pass

class PaymentAdapter(ABC):
    @abstractmethod
    def generate_request(self, order):
        pass

    @abstractmethod
    def check_status(self, trade_no):
        pass

class AliPayAdapter(PaymentAdapter):
    def generate_request(self, order):
        # 实际应调用支付宝API生成支付请求
        return {
            'trade_no': 'ALIPAY_{}'.format(order['id']),
            'qr_code': 'https://example.com/alipay_qr/{}'.format(order['id'])
        }

    def check_status(self, trade_no):
        # 模拟查询支付状态
        return {'success': True, 'msg': '支付成功'}

class WechatPayAdapter(PaymentAdapter):
    def generate_request(self, order):
        # 实际应调用微信支付API生成支付请求
        return {
            'trade_no': 'WECHAT_{}'.format(order['id']),
            'qr_code': 'https://example.com/wechat_qr/{}'.format(order['id'])
        }

    def check_status(self, trade_no):
        # 模拟查询支付状态
        return {'success': True, 'msg': '支付成功'}

class BankTransferAdapter(PaymentAdapter):
    def generate_request(self, order):
        # 生成银行转账信息
        return {
            'trade_no': 'BANK_{}'.format(order['id']),
            'account': '1234567890',
            'amount': order['amount']
        }

    def check_status(self, trade_no):
        # 模拟查询支付状态
        return {'success': False, 'msg': '银行转账待确认'}

class PaymentGateway:
    PAYMENT_METHODS = {
        'alipay': AliPayAdapter,
        'wechat': WechatPayAdapter,
        'bank': BankTransferAdapter
    }

    def __init__(self, config):
        self.default_method = config.get('default_method', 'alipay')
        self.method = self.PAYMENT_METHODS[self.default_method]()

    def process_payment(self, order, method=None):
        """执行支付流程"""
        adapter = self.method if not method else self.PAYMENT_METHODS[method]()

        try:
            # 生成支付请求
            payment_data = adapter.generate_request(order)

            # 这里可以添加GUI显示支付信息的逻辑（假设已连接到主窗口）
            # main_window = ...  # 获取主窗口实例
            # main_window.show_payment_info(payment_data)

            # 轮询支付结果（简化处理，实际应设置超时）
            result = adapter.check_status(payment_data['trade_no'])
            return PaymentResult(result['success'], result['msg'])
        except Exception as e:
            return PaymentResult(False, str(e))